/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.service.impl;

import com.minierp.bean.GatherBillBean;
import com.minierp.bean.GatherBillItemBean;
import com.minierp.bean.UserBean;
import com.minierp.dao.CooperBillItemDao;
import com.minierp.dao.GatherBillDao;
import com.minierp.dao.GatherBillItemDao;
import com.minierp.dao.IdGenerator;
import com.minierp.dao.SerialNumberDao;
import com.minierp.err.DataChangedException;
import com.minierp.err.NotAllowException;
import com.minierp.helper.PageHelper;
import com.minierp.model.CodeRule;
import com.minierp.model.CooperBill;
import com.minierp.model.CooperBillExt;
import com.minierp.model.CooperBillItem;
import com.minierp.model.GatherBill;
import com.minierp.model.GatherBillItem;
import com.minierp.model.SystemLog;
import com.minierp.service.GatherBillService;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class GatherBillServiceImpl implements GatherBillService {
	public void txInsert(GatherBillBean form, GatherBillDao gatherBillDao,
			GatherBillItemDao gatherBillItemDao,
			CooperBillItemDao cooperBillItemDao,
			SerialNumberDao serialNumberDao, IdGenerator idGenerator)
			throws Exception {
		GatherBill obj = form.getGatherBill();
		obj.setCreateTime(new Date());
		obj.setId(idGenerator.getId(GatherBill.class.getName()));
		if (!form.getCodeRule().getGenerateRule().equals("MANUAL")) {
			obj.setBillCode(PageHelper.generateCode(serialNumberDao, form
					.getCodeRule(), "", form.getGatherBill().getTallySetId()));

			for (GatherBill gathList = gatherBillDao.get(obj.getBillCode()); gathList != null; gathList = gatherBillDao
					.get(obj.getBillCode())) {
				obj.setBillCode(PageHelper.generateCode(serialNumberDao, form
						.getCodeRule(), "", form.getGatherBill()
						.getTallySetId()));
			}
		}

		List arg10 = gatherBillDao.getListByCooperBill(obj.getCooperBillId());

		for (int j = 0; j < arg10.size(); ++j) {
			GatherBill rb = (GatherBill) arg10.get(j);
			if (rb.getExamined().equals("N")) {
				throw new NotAllowException(
						"该外协单存在未审核的收货单，收货单号为"
								+ rb.getBillCode()
								+ "，请进入【外协-收货单一览表】找到这张收货单，把这张开过的未审核收货单审核通过就可以了，不需要再开收货单。");
			}
		}

		if (obj.getExamined().equals("Y")) {
			obj.setExamineTime(new Date());
		}

		gatherBillDao.save(obj);
		this.saveItems(form, gatherBillItemDao, cooperBillItemDao, idGenerator);
	}

	public void txInsertBatch(String[] idArr, UserBean ub, CodeRule dbCr,
			GatherBillDao gatherBillDao, GatherBillItemDao gatherBillItemDao,
			CooperBillItemDao cooperBillItemDao,
			SerialNumberDao serialNumberDao, IdGenerator idGenerator)
			throws Exception {
		if (dbCr == null) {
			throw new Exception("Code rule not found for gather bill");
		} else {
			for (int i = 0; i < idArr.length; ++i) {
				long cooperBillId = Long.parseLong(idArr[i]);
				CooperBill b = (CooperBill) cooperBillItemDao.get(
						CooperBill.class, cooperBillId);
				CooperBillExt be = (CooperBillExt) cooperBillItemDao.get(
						CooperBillExt.class, cooperBillId);
				List bbItemList = cooperBillItemDao.getList(cooperBillId);
				List gathList = gatherBillDao.getListByCooperBill(cooperBillId);

				GatherBill gatherBill;
				for (int form = 0; form < gathList.size(); ++form) {
					gatherBill = (GatherBill) gathList.get(form);
					if (gatherBill.getExamined().equals("N")) {
						throw new NotAllowException(
								"外协单"
										+ b.getBillCode()
										+ "存在未审核的收货单，收货单号为"
										+ gatherBill.getBillCode()
										+ "，请进入【外协-收货单一览表】找到这张收货单，把这张开过的未审核收货单审核通过就可以了，不需要再开收货单。");
					}
				}

				GatherBillBean arg22 = new GatherBillBean();
				gatherBill = new GatherBill();
				gatherBill.setCooperBillId(cooperBillId);
				gatherBill.setContent(b.getContent());
				gatherBill.setMark(b.getGatherRequire());
				if (gatherBill.getMark() != null
						&& gatherBill.getMark().length() > 100) {
					gatherBill.setMark(gatherBill.getMark().substring(0, 90)
							+ "...");
				}

				gatherBill.setCreaterId(ub.getStaffer().getId());
				gatherBill.setCreaterName(ub.getStaffer().getStafferName());
				gatherBill.setExaminerId(ub.getStaffer().getId());
				gatherBill.setExaminerName(ub.getStaffer().getStafferName());
				gatherBill.setTallySetId(ub.getUser().getDfTsId());
				gatherBill.setCreateTime(new Date());
				gatherBill.setId(idGenerator.getId(GatherBill.class.getName()));
				if (dbCr.getGenerateRule().equals("MANUAL")) {
					throw new NotAllowException("收货单编码规则必须设置为自动产生！");
				}

				gatherBill.setBillCode(PageHelper.generateCode(serialNumberDao,
						dbCr, "", gatherBill.getTallySetId()));

				for (GatherBill itemList = gatherBillDao.get(gatherBill
						.getBillCode()); itemList != null; itemList = gatherBillDao
						.get(gatherBill.getBillCode())) {
					gatherBill.setBillCode(PageHelper.generateCode(
							serialNumberDao, dbCr, "",
							gatherBill.getTallySetId()));
				}

				gatherBill.setExamined("Y");
				gatherBill.setExamineTime(new Date());
				gatherBillDao.save(gatherBill);
				ArrayList arg23 = new ArrayList();

				for (int j = 0; j < bbItemList.size(); ++j) {
					CooperBillItem bitem = (CooperBillItem) bbItemList.get(j);
					GatherBillItemBean cb = new GatherBillItemBean();
					GatherBillItem c = new GatherBillItem();
					c.setCbItemId(bitem.getId());
					c.setAmount(bitem.getAmount().subtract(
							bitem.getGatheredAmount()));
					cb.setGatherBillItem(c);
					arg23.add(cb);
				}

				arg22.setItems(arg23);
				arg22.setGatherBill(gatherBill);
				this.saveItems(arg22, b, be, bbItemList, gatherBillItemDao,
						idGenerator);
			}

		}
	}

	public void txUpdate(GatherBillBean form, GatherBillDao gatherBillDao,
			GatherBillItemDao gatherBillItemDao,
			CooperBillItemDao cooperBillItemDao, IdGenerator idGenerator)
			throws Exception {
		GatherBill obj = form.getGatherBill();
		Object[] sv = gatherBillDao.getStatusValues(obj.getId());
		if (sv == null) {
			throw new Exception("Can\'t get status values for gather bill:"
					+ obj.getId());
		} else {
			long existSycVal = ((Date) sv[0]).getTime();
			String exitEnabled = sv[1].toString();
			String existExamined = sv[2].toString();
			if (existSycVal != form.getSychronizeValue()) {
				throw new DataChangedException("收货单已被其他操作修改，请关闭页面再打开后重新操作！");
			} else if (exitEnabled.equals("N")) {
				throw new NotAllowException("收货单已作废，不能修改！");
			} else if (existExamined.equals("Y")) {
				throw new NotAllowException("收货单已审核，不能修改！");
			} else {
				if (obj.getExamined().equals("Y")) {
					obj.setExamineTime(new Date());
				}

				obj.setUpdateTime(new Date());
				gatherBillDao.update(obj);
				this.saveItems(form, gatherBillItemDao, cooperBillItemDao,
						idGenerator);
			}
		}
	}

	private void saveItems(GatherBillBean form, CooperBill b, CooperBillExt be,
			List<?> bbItemList, GatherBillItemDao gatherBillItemDao,
			IdGenerator idGenerator) throws Exception {
		List items = form.getItems();
		if (b == null) {
			throw new NotAllowException("找不到id为"
					+ form.getGatherBill().getCooperBillId() + "的外协单");
		} else if (be.getExamined().equals("N")) {
			throw new NotAllowException("外协单还没审核，不能收货。单号：" + b.getBillCode());
		} else if (be.getEnabled().equals("N")) {
			throw new NotAllowException("外协单已作废，不能收货。单号：" + b.getBillCode());
		} else {
			int newNum = 0;

			for (int curItemId = 0; curItemId < items.size(); ++curItemId) {
				GatherBillItemBean bean = (GatherBillItemBean) items
						.get(curItemId);
				if (bean.getOldId() == 0L
						&& bean.getGatherBillItem().getAmount()
								.compareTo(new BigDecimal(0)) == 1) {
					++newNum;
				}
			}

			long arg19 = 0L;
			if (newNum > 0) {
				arg19 = idGenerator.getId(GatherBillItem.class.getName(),
						newNum);
			}

			boolean coopUpd = false;

			for (int gathered = 0; gathered < items.size(); ++gathered) {
				GatherBillItemBean hasItemGath = (GatherBillItemBean) items
						.get(gathered);
				long j = hasItemGath.getGatherBillItem().getCbItemId();
				hasItemGath.getGatherBillItem().setBillId(
						form.getGatherBill().getId());
				boolean checkGathered = false;
				if (hasItemGath.getOldId() != 0L) {
					if (hasItemGath.getGatherBillItem().getAmount()
							.compareTo(new BigDecimal(0)) == 0) {
						gatherBillItemDao.delete(hasItemGath
								.getGatherBillItem().getId());
					} else {
						gatherBillItemDao.update(hasItemGath
								.getGatherBillItem());
						checkGathered = true;
					}
				} else if (hasItemGath.getGatherBillItem().getAmount()
						.compareTo(new BigDecimal(0)) == 1) {
					hasItemGath.getGatherBillItem().setId(arg19);
					gatherBillItemDao.save(hasItemGath.getGatherBillItem());
					++arg19;
					checkGathered = true;
				}

				CooperBillItem bbItem1 = null;
				boolean foundBbItem = false;

				for (int deliveredAmount = 0; deliveredAmount < bbItemList
						.size(); ++deliveredAmount) {
					bbItem1 = (CooperBillItem) bbItemList.get(deliveredAmount);
					if (bbItem1.getId() == j) {
						foundBbItem = true;
						break;
					}
				}

				if (foundBbItem) {
					if (checkGathered) {
						BigDecimal arg23 = gatherBillItemDao
								.getGatheredAmount(j);
						if (arg23.compareTo(bbItem1.getAmount()) == 1) {
							throw new NotAllowException("收货数量不能超过外协数量，请修正！");
						}
					}

					if (form.getGatherBill().getExamined().equals("Y")
							&& checkGathered) {
						bbItem1.setGatheredAmount(bbItem1.getGatheredAmount()
								.add(hasItemGath.getGatherBillItem()
										.getAmount()));
						gatherBillItemDao.update(bbItem1);
						coopUpd = true;
					}
				}
			}

			if (coopUpd) {
				b.setUpdateTime(new Date());
				gatherBillItemDao.update(b);
			}

			String arg20 = "Y";
			String arg21 = "N";

			for (int arg22 = 0; arg22 < bbItemList.size(); ++arg22) {
				CooperBillItem bbItem = (CooperBillItem) bbItemList.get(arg22);
				if (bbItem.getGatheredAmount().compareTo(new BigDecimal(0)) == 0) {
					arg20 = "N";
					if (arg21.equals("Y")) {
						arg20 = "P";
						break;
					}
				} else {
					if (bbItem.getAmount()
							.compareTo(bbItem.getGatheredAmount()) != 0) {
						arg20 = "P";
						break;
					}

					arg21 = "Y";
				}
			}

			be.setGathered(arg20);
			be.setHasGather("Y");
			gatherBillItemDao.update(be);
		}
	}

	private void saveItems(GatherBillBean form,
			GatherBillItemDao gatherBillItemDao,
			CooperBillItemDao cooperBillItemDao, IdGenerator idGenerator)
			throws Exception {
		CooperBill b = (CooperBill) cooperBillItemDao.get(CooperBill.class,
				form.getGatherBill().getCooperBillId());
		CooperBillExt be = (CooperBillExt) cooperBillItemDao.get(
				CooperBillExt.class, form.getGatherBill().getCooperBillId());
		List bbItemList = cooperBillItemDao.getList(b.getId());
		this.saveItems(form, b, be, bbItemList, gatherBillItemDao, idGenerator);
	}

	public void txExamine(long id, GatherBillDao gatherBillDao,
			GatherBillItemDao gatherBillItemDao,
			CooperBillItemDao cooperBillItemDao, long examinerId,
			String examinerName) throws Exception {
		GatherBill a = (GatherBill) gatherBillDao.get(GatherBill.class, id);
		if (a != null && a.getEnabled().equals("Y")
				&& a.getExamined().equals("N")) {
			List itemList = gatherBillItemDao.getListByGatherBill(a.getId());
			a.setExamined("Y");
			a.setExamineTime(new Date());
			a.setExaminerId(examinerId);
			a.setExaminerName(examinerName);
			a.setUpdateTime(new Date());
			gatherBillDao.update(a);
			this.updateCooperBill(itemList, cooperBillItemDao,
					a.getCooperBillId(), true, false, gatherBillDao);
		}

	}

	private void updateCooperBill(List<?> itemList,
			CooperBillItemDao cooperBillItemDao, long cooperBillId,
			boolean isAdd, boolean checkHasGather, GatherBillDao gatherBillDao)
			throws Exception {
		CooperBill b = (CooperBill) cooperBillItemDao.get(CooperBill.class,
				cooperBillId);
		CooperBillExt be = (CooperBillExt) cooperBillItemDao.get(
				CooperBillExt.class, cooperBillId);
		if (b == null) {
			throw new NotAllowException("找不到id为" + cooperBillId + "的外协单");
		} else if (be.getExamined().equals("N")) {
			throw new NotAllowException("单号为" + b.getBillCode()
					+ "的外协单还没审核，不能操作");
		} else if (be.getEnabled().equals("N")) {
			throw new NotAllowException("单号为" + b.getBillCode()
					+ "的外协单已作废，不能操作");
		} else {
			List bbItemList = cooperBillItemDao.getList(b.getId());

			for (int gathered = 0; gathered < itemList.size(); ++gathered) {
				GatherBillItem hasItemGath = (GatherBillItem) itemList
						.get(gathered);
				BigDecimal j;
				if (isAdd) {
					j = hasItemGath.getAmount();
				} else {
					j = (new BigDecimal(0)).subtract(hasItemGath.getAmount());
				}

				for (int bbItem = 0; bbItem < bbItemList.size(); ++bbItem) {
					CooperBillItem bbItem1 = (CooperBillItem) bbItemList
							.get(bbItem);
					if (bbItem1.getId() == hasItemGath.getCbItemId()) {
						bbItem1.setGatheredAmount(bbItem1.getGatheredAmount()
								.add(j));
						cooperBillItemDao.update(bbItem1);
						break;
					}
				}
			}

			b.setUpdateTime(new Date());
			cooperBillItemDao.update(b);
			if (checkHasGather) {
				List arg15 = gatherBillDao.getListByCooperBill(b.getId());
				if (arg15.size() > 0) {
					be.setHasGather("Y");
				} else {
					be.setHasGather("N");
				}
			}

			String arg16 = "Y";
			String arg17 = "N";

			for (int arg18 = 0; arg18 < bbItemList.size(); ++arg18) {
				CooperBillItem arg19 = (CooperBillItem) bbItemList.get(arg18);
				if (arg19.getGatheredAmount().compareTo(new BigDecimal(0)) == 0) {
					arg16 = "N";
					if (arg17.equals("Y")) {
						arg16 = "P";
						break;
					}
				} else {
					if (arg19.getAmount().compareTo(arg19.getGatheredAmount()) != 0) {
						arg16 = "P";
						break;
					}

					arg17 = "Y";
				}
			}

			be.setGathered(arg16);
			cooperBillItemDao.update(be);
		}
	}

	public void txUnExamine(long id, GatherBillDao gatherBillDao,
			GatherBillItemDao gatherBillItemDao,
			CooperBillItemDao cooperBillItemDao) throws Exception {
		GatherBill a = (GatherBill) gatherBillDao.get(GatherBill.class, id);
		if (a != null && a.getEnabled().equals("Y")
				&& a.getExamined().equals("Y")) {
			a.setExamined("N");
			a.setExaminerId(0L);
			a.setExaminerName("");
			a.setUpdateTime(new Date());
			gatherBillDao.update(a);
			List itemList = gatherBillItemDao.getListByGatherBill(a.getId());
			this.updateCooperBill(itemList, cooperBillItemDao,
					a.getCooperBillId(), false, false, gatherBillDao);
		}

	}

	public void txCancel(long id, String reason, GatherBillDao gatherBillDao,
			GatherBillItemDao gatherBillItemDao,
			CooperBillItemDao cooperBillItemDao, UserBean ub,
			IdGenerator idGenerator) throws Exception {
		GatherBill d = (GatherBill) gatherBillDao.get(GatherBill.class, id);
		if (d != null && d.getEnabled().equals("Y")) {
			d.setEnabled("N");
			d.setDisableManId(ub.getUser().getStafferId());
			d.setUpdateTime(new Date());
			gatherBillDao.update(d);
			if (d.getExamined().equals("Y")) {
				List log = gatherBillItemDao.getListByGatherBill(d.getId());
				this.updateCooperBill(log, cooperBillItemDao,
						d.getCooperBillId(), false, true, gatherBillDao);
			} else {
				CooperBill log1 = (CooperBill) gatherBillDao.get(
						CooperBill.class, d.getCooperBillId());
				CooperBillExt be = (CooperBillExt) gatherBillDao.get(
						CooperBillExt.class, d.getCooperBillId());
				if (log1 == null) {
					throw new NotAllowException("找不到id为" + d.getCooperBillId()
							+ "的外协单");
				}

				if (be.getExamined().equals("N")) {
					throw new NotAllowException("单号为" + log1.getBillCode()
							+ "的外协单还没审核，不能操作");
				}

				if (be.getEnabled().equals("N")) {
					throw new NotAllowException("单号为" + log1.getBillCode()
							+ "的外协单已作废，不能操作");
				}

				List iList = gatherBillDao.getListByCooperBill(d
						.getCooperBillId());
				if (iList.size() > 0) {
					be.setHasGather("Y");
				} else {
					be.setHasGather("N");
				}

				gatherBillDao.update(be);
			}

			SystemLog log2 = new SystemLog();
			log2.setId(idGenerator.getId(SystemLog.class.getName()));
			log2.setActionCode("GATHER_BILL");
			log2.setLogType("CANCEL_LOG");
			log2.setCreaterId(ub.getStaffer().getId());
			log2.setCreaterName(ub.getStaffer().getStafferName());
			log2.setDepName(ub.getDepName());
			log2.setDepId(ub.getStaffer().getDepartmentId());
			log2.setStatus("S");
			log2.setUserName(ub.getUser().getUserName());
			log2.setIp(d.getBillCode());
			log2.setMark("");
			log2.setRelId(id);
			log2.setCancelReason(reason);
			log2.setTallySetId(d.getTallySetId());
			gatherBillDao.save(log2);
		}

	}
}